package com.yy.permissions_general.module.system.mail.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.permissions_general.common.config.exception.base.ServiceException;
import com.yy.permissions_general.module.system.mail.entity.Mail;
import com.yy.permissions_general.module.system.mail.mapper.MailMapper;
import com.yy.permissions_general.module.system.mail.service.MailService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 邮箱 服务实现类
 * </p>
 *
 * @author YY
 * @since 2022-02-10
 */
@Service
public class MailServiceImpl extends ServiceImpl<MailMapper, Mail> implements MailService {

    @Resource
    private MailAccount mailAccount;

    /**
    * 分页查询列表
    * @param mail
    * @return
    */
    @Override
    public  Page<Mail>selectPageList(Mail mail, int limit, int page)  {
        Page pageContext = new Page(page,limit);
        Page<Mail> pageList = this.baseMapper.selectPage(pageContext, mail);
        return pageList;
    }

    /**
    * 新增数据
    * @param mail
    */
    @Override
    public int addMail(Mail mail) {
        if (!sendMail(mail)){
            throw new ServiceException(500, "请检查邮箱配置~");
        }
        return baseMapper.insert(mail);
    }

    @Override
    public Boolean sendMail(Mail mail) {
        ArrayList<String> tos = CollectionUtil.newArrayList(StrUtil.split(mail.getReceiver(), ";"));
        String send = MailUtil.send(mailAccount, tos, ObjectUtil.isEmpty(mail.getSubject()) ? null : mail.getSubject(), mail.getContent(), false);
        return ObjectUtil.isNotEmpty(send);
    }


    /**
    * 查看详情
    * @param id
    * @return
    */
    @Override
    public Mail getDetailsById(String id) {
        return baseMapper.selectById(id);
    }

    /**
    * 删除数据
    * @param id
    * @return
    */
    @Override
    public int deleteById(String id) {
        return baseMapper.deleteById(id);
    }

    /**
    * 批量删除
    * @param ids
    * @return
    */
    @Override
    public int deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

}

